package com.luckdraw.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.nutz.http.Http;
import org.nutz.http.Response;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import com.alibaba.fastjson.JSONObject;
import com.luckdraw.domain.Activity;
import com.luckdraw.domain.CommissionLog;
import com.luckdraw.domain.User;
import com.luckdraw.service.ActivityService;
import com.luckdraw.service.GameService;
import com.luckdraw.service.TenpayService;

@IocBean
@InjectName
@At("/activity")
public class LuckDrawMobule {
	
	@Inject
	ActivityService luckDrawService;
	
	@Inject
	private GameService gameService;
	
	@Inject
	private TenpayService tenpayService;
	
	@Inject("java:$conf.get('tenpay.appId')")
	private String appId;
	
	@Inject("java:$conf.get('weixin.api.secret')")
	private String weixinSecret;
	
	@Inject("java:$conf.get('weixin.api.mch_id')")
	private String mch_id;
	
	@Inject("java:$conf.get('hongbao.homePage')")
	private String homePage;
	
	@Inject("java:$conf.get('hongbao.baseUrl')")
	private String baseUrl;
	
	/**
	 * 活动列表
	 * @return
	 */
	@At("/?/list")
	public Object list(HttpServletRequest request){
		HttpSession session = request.getSession();
		String userId = (String)session.getAttribute("openid");
		if(Strings.isNotBlank(userId)){
			List<Activity> list = luckDrawService.getLuckDrawSetList();
			List<NutMap> dataList = new ArrayList<NutMap>();
			if(list!=null&&list.size()>0){
				for(Activity set:list){
					dataList.add(NutMap.NEW().addv("id", set.getId()).addv("payAmount", set.getCost()));
				}
			}
			return NutMap.NEW().addv("code", 0).addv("data", dataList);
		}else{
			return NutMap.NEW().addv("code", 99).addv("data", "请在公众号中打开。");
		}
	}
	  
	/**
	 * 抽奖
	 * @param request
	 * @param setId
	 * @return
	 */
	@At("/?/luckdraw")
	public Object luckdraw(HttpServletRequest request,@Param("id")int setId){
		HttpSession session = request.getSession();
		String openId = (String)session.getAttribute("openid");
		NutMap resultMap = new NutMap();
		if(Strings.isEmpty(openId)){
			resultMap.addv("code", 99).addv("data", "请在公众号内操作");
		}else{
			Activity set = luckDrawService.getLuckDrawSet(setId);
			if(set==null||set.getStatus()==0){
				resultMap.addv("code", 1).addv("data", "活动已结束");
			}else{
				String prepayId = luckDrawService.createOrder(openId, setId);
				resultMap.addv("code", 0).addv("data", tenpayService.getJsPayRequestInfo(prepayId));
			}
		}
		return resultMap;
	}
	
	/**
	 * 红包列表
	 * @param userId
	 * @return
	 */
	@At("/partakeList")
	public Object partakeList(HttpServletRequest request){
		HttpSession session = request.getSession();
		String userId = (String)session.getAttribute("openid");
		if(Strings.isNotBlank(userId)){
			User user =luckDrawService.getUser(userId); 
			return NutMap.NEW().addv("code", 0).addv("data", NutMap.NEW().addv("amount", user.getAmount()).addv("partake", luckDrawService.getLuckDrawLogList(userId)));
		}else{
			return NutMap.NEW().addv("code", 99).addv("data", "请在公众号中打开。");
		}
	}
	
	/**
	 * 佣金获取列表
	 * @param userId
	 * @return
	 */
	@At("/commission")
	public Object commission(HttpServletRequest request){
		HttpSession session = request.getSession();
		String userId = (String)session.getAttribute("openid");
		if(Strings.isNotBlank(userId)){
			List<CommissionLog> logs = luckDrawService.getCommissionLogs(userId);
			List<NutMap> dataList = new ArrayList<NutMap>();
			for(CommissionLog log:logs){
				NutMap logMap = NutMap.NEW();
				logMap.addv("nickName", log.getSubNickName2());
				logMap.addv("payTime", log.getPayTime());
				logMap.addv("payAmount", log.getPayAmount());
				logMap.addv("amount", log.getCommission());
				dataList.add(logMap);
			}
			return NutMap.NEW().addv("code", 0).addv("data", dataList);
		}else{
			return NutMap.NEW().addv("code", 99).addv("data", "请在公众号中打开。");
		}
	}
	
	/**
	 * 提现
	 * @param userId
	 * @return
	 */
	@At("/withdrawals")
	public Object withdrawals(HttpServletRequest request){
		HttpSession session = request.getSession();
		String userId = (String)session.getAttribute("openid");
		if(Strings.isNotBlank(userId)){
			NutMap map;
			int i = luckDrawService.countwithdrawalTimes(userId);
			if(i > 100){
				map=NutMap.NEW().addv("code", 1).addv("data", "24小时内提现次数不能超过100次!");
			}
			if(luckDrawService.withdrawals(userId,mch_id,appId)){
				map = NutMap.NEW().addv("code", 0).addv("data", "提现成功,请您在公众号“北京青策文化传播有限公司”领取红包！");
			}else{
				map = NutMap.NEW().addv("code", 1).addv("data", "余额不足！");
			}
			return map;
		}else{
			return NutMap.NEW().addv("code", 99).addv("data", "请在公众号中打开。");
		}
	}

	/**
	 * 网页授权获得openId
	 */
	@At("/tok/?")
	@Ok("re")
	public String tok(String page,HttpServletRequest req){
        String code=req.getParameter("code");
        HttpSession session= req.getSession();
       if(null !=code && !code.equals("")){
        	String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="
					+appId+"&secret="+weixinSecret+"&code="+code+"&grant_type=authorization_code";
        	try {
        		String res = "";
        		Response response = Http.get(url);
        		res = response.getContent();
				JSONObject ob = (JSONObject)JSONObject.parse(res.toString());
				String openid=(String) ob.get("openid");
				session.setAttribute("openid",openid);
				//注册用户,用户存在或者注册成功时才将openid存入session
				String agent = (String)session.getAttribute("agent");
				if(luckDrawService.register(openid, agent)){
					session.setAttribute("openid",openid);
				}
				if(Strings.isNotBlank(page)){
					return ">>:/"+page+".html";
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
       return "jsp:page.error.404";
	}
	
	/**
	 * 生成代理链接
	 * @param request
	 * @return
	 */
	@At("/agent")
	public Object agent(HttpServletRequest request){
		String userId = (String)request.getSession().getAttribute("openid");
		if(Strings.isNotBlank(userId)){
			return NutMap.NEW().addv("code", 0).addv("data", homePage+"?agent="+userId);
		}else{
			return NutMap.NEW().addv("code", 0).addv("data", homePage);
		}
	}
	
	/**
	 * 入口页
	 * @param response
	 * @throws IOException
	 */
	@At("/homePage/?")
	@Ok("void")
	public void index(String page,@Param("agent")String agent,HttpServletRequest request,HttpServletResponse response) throws IOException{
		if(Strings.isNotBlank(agent)){
			request.getSession().setAttribute("agent", agent);
		}
		String redirect_uri = Http.encode(baseUrl+"activity/tok/"+page);
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_base&state=#wechat_redirect";
		response.sendRedirect(url);
	}
	
	/**
	 * 中奖滚动列表
	 * @param request
	 * @return
	 */
	@At("/lkc")
	public Object lkc(){
		List<NutMap> list = new ArrayList<NutMap>();
		NutMap m = NutMap.NEW();
		m.addv("amount",55.26).addv("name", "蚂蚁闹钟");
		list.add(m);
		
		NutMap m1 = NutMap.NEW();
		m1.addv("amount",90.80).addv("name", "赵云");
		list.add(m1);
		
		NutMap m2 = NutMap.NEW();
		m2.addv("amount",45.54).addv("name", "zbb");
		list.add(m2);
		
		NutMap m3 = NutMap.NEW();
		m3.addv("amount",88).addv("name", "周亚");
		list.add(m3);
		
		NutMap m4 = NutMap.NEW();
		m4.addv("amount",72.95).addv("name", "有钱哥");
		list.add(m4);
		
		NutMap m5 = NutMap.NEW();
		m5.addv("amount",48.32).addv("name", "非凡");
		list.add(m5);
		
		NutMap m6 = NutMap.NEW();
		m6.addv("amount",82.58).addv("name", "小鲜肉");
		list.add(m6);
		
		NutMap m7 = NutMap.NEW();
		m7.addv("amount",68.49).addv("name", "阳刚");
		list.add(m7);
		
		NutMap m8 = NutMap.NEW();
		m8.addv("amount",88.28).addv("name", "巴山居士");
		list.add(m8);
		
		NutMap m9 = NutMap.NEW();
		m9.addv("amount",87.85).addv("name", "无敌盲僧");
		list.add(m9);
		
		NutMap m10 = NutMap.NEW();
		m10.addv("amount",88.88).addv("name", "前台吴");
		list.add(m10);
		
		NutMap m11 = NutMap.NEW();
		m11.addv("amount",78).addv("name", "哈哈");
		list.add(m11);
		
		NutMap m12 = NutMap.NEW();
		m12.addv("amount",98.66).addv("name", "哎哟哟");
		list.add(m12);
		
		NutMap m13 = NutMap.NEW();
		m13.addv("amount",76.39).addv("name", "小老头");
		list.add(m13);
		
		NutMap m14 = NutMap.NEW();
		m14.addv("amount",96.48).addv("name", "soraya");
		list.add(m14);
		
		NutMap mx = NutMap.NEW();
		mx.addv("list", list);
		return mx;
	}
	
	/**
	 * 判断用户是否关注公众号
     * eg: https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
	 */
	@At("/isConcern")
	public Object isConcern(HttpServletRequest request){
		HttpSession session = request.getSession();
		String weixinOpenId = (String)session.getAttribute("openid");
		if(Strings.isBlank(weixinOpenId)){
			return NutMap.NEW().addv("code",2).addv("msg", "未登录!");
		}
		return luckDrawService.isConcern(weixinOpenId);
	}
	
	
	
}
